package com.mindskip.xzs.configuration.spring.wx;

import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.configuration.spring.security.RestUtil;
import com.mindskip.xzs.constant.CommonRedisKey;
import com.mindskip.xzs.context.WxContext;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.domain.UserToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class TokenHandlerInterceptor implements HandlerInterceptor {
    @Resource
    RedisTemplate<String, User> redisTemplate;

    private final WxContext wxContext;

    /**
     * 小程序token过期时间
     */
    @Value("${system.wx.token-to-live}")
    private Long timeout;

    @Autowired
    public TokenHandlerInterceptor(WxContext wxContext) {
        this.wxContext = wxContext;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        if (StringUtils.isBlank(token)) {
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        if (token.length() != 36) {
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }

        User user = redisTemplate.opsForValue().get(CommonRedisKey.EMPLOYEE_QYWX_XCX_LOGIN_KEY + token);

        if (null == user) {
            // 微信环境适配
          // UserToken userToken = userTokenService.getToken(token);
          // if (null != userToken) {
          //     Date now = new Date();
          //     User user1 = userService.getUserByUserName(userToken.getUserName());
          //     if (now.before(userToken.getEndTime())) {
          //         wxContext.setContext(user1,userToken);
          //         return true;
          //     } else {   //refresh token
          //         UserToken refreshToken = userTokenService.insertUserToken(user1);
          //         RestUtil.response(response, SystemCode.AccessTokenError.getCode(), SystemCode.AccessTokenError.getMessage(), refreshToken.getToken());
          //         return false;
          //     }
          // }
            RestUtil.response(response, SystemCode.UNAUTHORIZED);
            return false;
        }
        // 刷新token
        redisTemplate.opsForValue().set(CommonRedisKey.EMPLOYEE_QYWX_XCX_LOGIN_KEY + token, user, timeout, TimeUnit.HOURS);
        wxContext.setContext(user, new UserToken().setUserId(user.getId()).setToken(token).setUserName(user.getUserName()));
        return true;
    }
}
